<template>
	<uni-popup ref="popup" background-color="#fff" :safe-area="true">
		<view class="popup-content">
			<div class="popup-wrap">
				<ly-tree :tree-data="data" :props="defaultProps" node-key="id" show-checkbox
					:default-checked-keys="checkedKeys" :defaultExpandAll="true"
					:expand-on-check-node="expandOnCheckNode" @check="handleCheck" />
			</div>
			<view class="popup-btns">
				<button class="popup_button" @click="close">取消</button>
				<button type="primary" class="popup_button" @click="submit">确定</button>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	import LyTree from '@/components/ly-tree/ly-tree.vue'
	import { deviceTree } from '@/api/map/index.js'

	export default {
		name: "devicesTree",
		components: {
			LyTree
		},
		data() {
			return {
				expandOnCheckNode: false,
				checkedKeys: [],
				deviceList: [],
				data: [],
				defaultProps: {
					children: 'children',
					label: 'label',
				},
			}
		},
		methods: {
			initData() {
				deviceTree({}).then(res => {
					if (res.code === "00000000") {
						this.data = this.trans_tree(res.data)
					}
				})
			},
			trans_tree(list = []) {
				return list.map(item => {
					const {
						deviceCameraName,
						regionName,
						deviceCameraId,
						regionId,
						children,
						isTreeNode,
						isTreeRegionNode,
						heartbeatStatus,
						...rest
					} = item,
					is_node = isTreeNode || isTreeRegionNode,
						res_item = {
							label: deviceCameraName || regionName,
							id: regionId || deviceCameraId,
							isLeaf: !is_node,
							checkable: !is_node || (is_node && children?.length > 0),
							children: !!children?.length ? this.trans_tree(children) : void 0,
							isTreeRegionNode,
							...rest
						}
					return res_item
				})
			},
			open() {
				this.$refs.popup.open('bottom')
				this.initData()
			},
			submit() {
				const id = this.deviceList.map(i => i.id)
				const labels = this.deviceList.map(i => i.label).join(',')
				this.$emit('onOk', id, labels)
				this.close()
			},
			close() {
				this.$refs.popup.close()
			},
			handleCheck(obj) {
				this.deviceList = obj.checkedNodes.filter(i => i.isLeaf)
			}
		}
	}
</script>

<style scoped>
	.popup-content {
		max-height: 85vh;
		padding-bottom: 200rpx;
		position: relative;
	}

	.popup-wrap {
		height: calc(85vh - 200rpx);
		overflow: auto;
	}

	.popup-btns {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		bottom: 120rpx;
	}

	.popup_button {
		height: 60rpx;
		line-height: 60rpx;
		width: 200rpx;
		font-size: 32rpx;
	}
</style>